<template>
	<view class="container">
		<uni-popup ref="popup" type="bottom">
			
			<view class="spec">
				<view class="close">
					<uni-icons type="closeempty" size="24" color="#8F8F8F" @click="closePopup()"></uni-icons>
				</view>
				<view class="info">
					<view class="left">
						<image mode="scaleToFill" :src="goodsShowInfo.thumbnail+'?x-oss-process=image/resize,w_200,h_200,m_fill'"
							@click="previewThumbnailImage()"></image>
					</view>
					<view class="right">
						<view class="title"><text :selectable="true">{{ goodsShowInfo.goodsName }}</text></view>
						<view class="price"><text>￥</text>{{ goodsShowInfo.goodsPrice/100 }}</view>
					</view>
				</view>
				<view class="spec-list">
					<view v-for="(item,index) in allSpecList" :key="index" class="item">
						<view class="spec-name">
							{{ item.specName }}
						</view>
						<view class="spec-value">
							<text v-for="(item2,index2) in item.specValueList" :key="index2"
								:class="{ active: selected.indexOf(item2.specValue) > -1, disable: !isCanSelect(item2.specValue,index) && selected.indexOf(item2.specValue) === -1 }"
								@click=" isCanSelect(item2.specValue,index)  && specSelect(item2.specValue,index)">
								{{ item2.specValue }}
							</text>
						</view>
					</view>
					
					<view class="item">
						<view class="spec-name">备注</view>
						<view class="spec-value">
							<uni-easyinput v-model="remark" placeholder="请输入" />
						</view>
					</view>
					
				</view>
				<view class="spec-num">
					<view class="left">购买数量</view>
					<view class="right">
						<uni-number-box v-model="goodsNum" :min="1" :max="goodsShowInfo.goodsStorage" />
					</view>
				</view>
				<view class="spec-btn-box">
					<button type="warn" class="spec-btn" @click="toOrder()">立即下单</button>
					<button type="primary" plain="true" class="spec-btn" @click="addCart()" mar>添加菜品</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import { GoodsApi } from '@/api/food/GoodsApi'
	import { DictApi } from '@/api/DictApi'
	import { ShoppingCartApi } from '@/api/food/ShoppingCartApi'
	import { OrderApi } from '@/api/food/OrderApi'
	
	export default {
		data() {
			return {
                Config:this.$Config,
                Common:this.$Common,
                Auth:this.$Auth,
                ShareUtil:this.$ShareUtil,
                State:this.$store.state,

				goodsShowInfo: {},
				goodsInfo: {},
				navActiveIndex: 0,

				bannerImageArr: [],
				detailImageArr: [],

				//处理规格数据start
				allSpecList: [], //规格完整数据
				items: [], //简化后的规格数据
				result: [], //商品的规格值
				selected: [], //已选择的规格项
				data: {}, //关键字规格集合
				//处理规格数据end

				goodsNum: 1,
				remark:'',
				
				dict: {},

				dotStyle: {
					backgroundColor: 'rgba(255, 255, 255, .5)',
					border: 'none',
					color: '#fff',
					selectedBackgroundColor: 'rgba(255, 255, 255, .9)',
					selectedBorder: 'none'
				},
				currentBannerIndex: 0,
				
			}
		},
		created() {
		},
		onLoad() {
            
		},
		
		methods: {
			show(mainGoodsId){
				let that = this
				
				that.allSpecList = []; //规格完整数据
				that.items = []; //简化后的规格数据
				that.result = []; //商品的规格值
				that.selected = []; //已选择的规格项
				that.data = {}; //关键字规格集合
				
				
				DictApi.getDict().then((response) => {
				    this.dict = response
				})
				
				that.getGoodsMainDetail(mainGoodsId, function() {
					that.showGoodsInfo(that.goodsInfo)
					that.initSpec()
				
					if (mainGoodsId) that.setChildGoodsInfo(mainGoodsId)
					
					that.openPopup()
				})
			},
			initPage: function() {
				
			},
			getGoodsMainDetail(mainGoodsId, callback) {
                GoodsApi.getGoodsMainDetail(mainGoodsId).then((response) => {
					this.goodsInfo = response
					callback()
				})
			},
            convertSpec(dataList){
                let result = []
                dataList.forEach(function (item, index, arr) {
                    let i = -1
                    result.forEach(function (cItem, cIndex, cArr) {
                        if (item.specId === cItem.specId) i = cIndex
                    })

                    if (i > -1) {
                        result[i].specValueList.push({
                            specValue: item.specValue,
                            specValueId: item.specValueId
                        })
                    } else {
                        let specObj = {
                            specId: item.specId,
                            specName: item.specName,
                            specType: item.specType,
                            specValueList: [{
                                specValue: item.specValue,
                                specValueId: item.specValueId
                            }]
                        }

                        result.push(specObj)
                    }
                })

                return result
            },
			showGoodsInfo(goodsData) {
				this.goodsShowInfo = goodsData
				this.goodsShowInfo.goodsStorage = parseInt(goodsData.goodsStorage)

				let goodsDetail = this.goodsShowInfo.goodsDetail
				goodsDetail = goodsDetail ? goodsDetail.replace(RegExp("<img", "g"), '<img style="width:100%;height:auto;display:block;"') : ''

				this.goodsShowInfo.goodsDetail = goodsDetail
                this.detailImageArr = this.Common.regexHtmlImg(goodsDetail)

				this.bannerImageArr = []
				this.goodsInfo.banner.forEach(item => {
					this.bannerImageArr.push(item.url)
				})

				this.allSpecList = this.convertSpec(goodsData.goodsSpecValueList.filter((item) => item.specType === 1))
				this.goodsShowInfo['goodsParam'] = goodsData.goodsSpecValueList.filter((item) => item.specType === 2)
			},
			previewBannerImage(index) {
                uni.previewImage({
                    current: index,
                    urls: this.bannerImageArr
                })
			},
			previewDetailImage() {
                uni.previewImage({
                    current: 0,
                    urls: this.detailImageArr
                })
			},
			previewThumbnailImage() {
                uni.previewImage({
                    current: 0,
                    urls: [this.goodsShowInfo.thumbnail]
                })
			},
			//初始化设置默认子商品
			setChildGoodsInfo(goodsId) {
				if (!goodsId) return

				let childList = this.goodsInfo.goodsSpecList.filter(v => v.id == goodsId)
				if (childList.length === 0) return

				let childInfo = childList[0]
				this.selected = childInfo.specKey.split('-')
				this.getChildGoodsByKey()
			},

			getChildGoodsByKey() {
				let selected = Object.assign([], this.selected)
				selected = selected.filter(v => v != null)
				if (selected.length !== this.allSpecList.length) {
					this.showGoodsInfo(this.goodsInfo)
				} else {
					let key = selected.join('-')
					let childGoodsList = this.goodsInfo.goodsSpecList.filter(v => v.specKey == key)
					if (childGoodsList.length == 1) {
						let childGoodsInfo = childGoodsList[0]

						let newGoods = Object.assign({}, this.goodsInfo)
						newGoods.id = childGoodsInfo.id
						newGoods.goodsName = childGoodsInfo.goodsName
						newGoods.goodsPrice = childGoodsInfo.goodsPrice
						newGoods.goodsStorage = childGoodsInfo.goodsStorage
						if (childGoodsInfo.goodsDetail) {
							newGoods.goodsDetail = childGoodsInfo.goodsDetail
						}
						if (childGoodsInfo.thumbnail) {
							newGoods.thumbnail = childGoodsInfo.thumbnail
						}
						if (childGoodsInfo.banner && childGoodsInfo.banner.length > 0) {
							newGoods.banner = childGoodsInfo.banner
						}

						this.showGoodsInfo(newGoods)
					}
				}
			},

			//初始化规格
			initSpec() {
				let that = this
				that.allSpecList.forEach(item => {
					let spec = []
					item.specValueList.forEach(value => {
						spec.push(value.specValue)
					})

					that.items.push(spec)
				})

				that.goodsInfo.goodsSpecList.forEach(item => {
					that.result[item.specKey] = {
						remain: item.goodsStorage,
						price: item.goodsPrice
					}
				})
			},
			//判断是否可选
			isCanSelect(value, index) {
				let newSelect = Object.assign([], this.selected)
				newSelect[index] = value

				let remain = this.getRemainByKey(newSelect)

				return remain > 0
			},
			//点击规格值
			specSelect(value, index) {
				if (this.selected[index] === value) {
					this.selected[index] = null
				} else {
					this.selected[index] = value
				}

				this.getChildGoodsByKey()
				this.goodsNum = 1
			},
			//取出关键字下的库存
			getRemainByKey(selected) {
				let that = this

				selected = selected.filter(v => v != null)
				const key = selected.join('-')

				if (typeof that.data[key] !== 'undefined') {
					return that.data[key]
				}

				if (selected.length === that.items.length) {
					return that.result[key] ? that.data[key] = that.result[key].remain : that.data[key] = 0
				}

				let remain = 0
				let tempSelected = []

				for (let i = 0; i < that.items.length; i++) {
					const exist = that.items[i].find(_item => _item === selected[0])
					if (exist && selected.length > 0) {
						tempSelected.push(selected.shift())
					} else {
						that.items[i].forEach(_item => {
							remain += that.getRemainByKey(tempSelected.concat(_item, selected))
						})
						break
					}
				}
				return that.data[key] = remain
			},

			openPopup() {
				if (!this.Auth.isLogin()) {
                    this.Auth.toLogin()
					return
				}

				this.$refs.popup.open('bottom')
			},

			closePopup() {
				this.$refs.popup.close()
			},

			//下拉刷新
			onRefresh() {},

			addCart() {
				if (this.goodsInfo.id === this.goodsShowInfo.id) {
					uni.showToast({
						title: "请选择商品规格",
						icon: 'none'
					})
					return
				}

				ShoppingCartApi.add({
					goodsId: this.goodsShowInfo.id,
					goodsNum: this.goodsNum,
					remark: this.remark
				}).then((response) => {
					this.$emit('refresh')
					this.closePopup()
				})
				
				
			},
			
			toOrder() {
				let that = this
				
				if (this.goodsInfo.id === this.goodsShowInfo.id) {
					uni.showToast({
						title: "请选择商品规格",
						icon: 'none'
					})
					return
				}
				
				uni.showModal({
					title: '提示',
					content: '确定点餐吗？',
					success: function (res) {
						if (res.confirm) {
							let data = {
								goodsParam:[{
									goodsId: that.goodsShowInfo.id,
									goodsNum: that.goodsNum,
									remark: that.remark
								}]
							}
							OrderApi.createOrder(data).then((response) => {
								uni.showToast({
									title: '点餐成功',
									icon: 'success'
								});
								that.closePopup()
							})
						}
					}
				});
				
			},

			pageScrollTo(index, id) {
				this.navActiveIndex = index
				uni.pageScrollTo({
					selector: "#" + id,
					duration: 300
				});
			},
			bannerChange(e) {
				this.currentBannerIndex = e.detail.current
			}
		}
	}
</script>

<style scoped>
	
	.spec {
		border-radius: 60rpx 60rpx 0 0;
		background: #FFFFFF;
		padding: 0 30rpx 30rpx 30rpx;
	}
	.spec .close {
		padding: 20rpx 0 10rpx 0;
		text-align: right;
	}
	.spec .info {
		display: flex;
	}
	.spec .info .left {
		width: 160rpx;
		height: 160rpx;
	}
	.spec .info .left image {
		width: 160rpx;
		height: 160rpx;
	}
	.spec .info .right {
		flex: 1;
		padding-left: 30rpx;
	}
	.spec .info .right .title {
		font-size: 32rpx;
		min-height: 84rpx;
	}
	.spec .info .right .price {
		font-size: 52rpx;
		color: #F81200;
		margin-top: 20rpx;
		font-weight: bold;
	}
	.spec .info .right .price text {
		font-size: 32rpx;
	}
	.spec .spec-list {
		margin-top: 44rpx;
	}
	.spec .spec-list .item {
		display:flex;
	}
	.spec .spec-list .item .spec-name {
		font-size: 32rpx;
		font-weight: bold;
		color: #232323;
		width:100rpx;
		padding-top:12rpx;
	}
	.spec .spec-list .item .spec-value {
		margin-bottom: 22rpx;
		display: flex;
		flex-direction: row;
		-webkit-flex-wrap: wrap;
		flex-wrap: wrap;
		flex:1;
	}
	.spec .spec-list .item .spec-value text {
		font-size: 32rpx;
		border: 1px solid #F1F1F1;
		border-radius: 40rpx;
		margin-right: 20rpx;
		padding: 14rpx 24rpx;
		margin-bottom: 20rpx;
		min-width: 80rpx;
		text-align: center;
	}
	.spec .spec-list .item .spec-value .active {
		border: 1px solid #E51422;
		color: #E51422;
		background-color: #FFF4F5;
	}
	.spec .spec-list .item .spec-value .disable {
		border: 1px solid #F1F1F1;
		color: #CCCCCC;
		background-color: #EEEEEE;
	}
	.spec .spec-num {
		display: flex;
		margin-bottom: 100rpx;
		margin-top:30rpx;
	}
	.spec .spec-num .left {
		flex: 1;
		font-size: 34rpx;
		font-weight: bold;
		color: #232323;
	}
	.spec .spec-num .right {
		width: 200rpx;
	}
	::v-deep .uni-numbox-btns {
		border-radius: 5px !important;
	}
	::v-deep .uni-numbox--text {
		color: #C0C0C0 !important;
	}
	::v-deep .uni-numbox__value {
		background: none !important;
		font-weight: bold;
	}
	::v-deep .uni-input-input {
		/* pointer-events: none; */
	}
	.spec-btn-box{ display:grid;  grid-template-columns:1fr 1fr;grid-gap:20px;}
	.spec-btn {
		border-radius: 50rpx;
		width:100%;
	}
</style>
